<?php

/**
 * Created by 深圳市丹宏昊天电子商务有限公司.
 * 作 者: sqingwen
 * 日 期: 2017/3/17
 * @property shipping_model $shipping_model
 * @property common_model $common_model
 */
class shipping extends MY_Controller
{

    function __construct()
    {
        parent::__construct();
        $this->load->model('shipping_model');
    }

    /**
     * 基础运费模板设置
     */
    public function basic()
    {
        $data = array();
        $data['listCountry'] = $this->db->query("select * from mt_country")->result_array();

        $this->load->view('defaults/shipping/basic' , $data);
    }

    public function ajaxLoadBasePrice()
    {
        $gp = gp();
        $page = intval($gp['page']);
        $rows = intval($gp['rows']);

        $dtPickup = trim($gp['dtPickUp']);
        $dtDelivery = trim($gp['dtDelivery']);
        $dtTplname = trim($gp['dtTplname']);

        $where = ' where 1=1 ';
        if (!empty($dtPickup)) {
            $where = $where . " and `pickup_country` like '%" . $dtPickup . "%'";
        }

        if (!empty($dtDelivery)) {
            $where = $where . " and `delivery_country` like '%" . $dtDelivery . "%'";
        }

        if (!empty($dtTplname)) {
            $where = $where . " and `tpl_name` like '%" . $dtTplname . "%'";
        }
        //计算总条数
        $sql_total = 'select count(`id`) as cnt from `mt_shipping_fee_basic`' . $where;
        $res_total = $this->db->query($sql_total)->row_array();
        $total = intval($res_total['cnt']);
        //计算总条数


        $sql = 'select * from `mt_shipping_fee_basic` ' . $where . ' order by id desc,tpl_code asc';
        if ($page > 0 && $rows > 0) {
            $start = (($page - 1) * $rows);
            $sql = $sql . ' limit ' . $start . ' , ' . $rows;
        }


        $res = $this->db->query($sql)->result_array();
        foreach ($res as $k => $v) {
            $res[$k]['weight'] = $v['begin_weight'] . ' - ' . $v['end_weight'];
            $res[$k]['shipping_type'] = $this->GetShippingType($v['shipping_type']);
            if (!empty($res[$k]['delivery_citys'])) {
                $res[$k]['delivery_country'] = $res[$k]['delivery_citys'];
            }
        }
        echo(json_encode(array('total' => $total , 'rows' => $res)));

        exit;
    }

    public function GetShippingType($id)
    {
        $str = '';
        switch ($id) {
            case 1:
                $str = '英国邮政Tracked（48H)签名服务';
                break;
            case 2:
                $str = '英国4PX速递服务';
                break;

            case 3:
                $str = '德国DHL欧盟区派送';
                break;

            case 4:
                $str = 'DHL';
                break;

            case 5:
                $str = 'USPS Medium Box';
                break;

            case 6:
                $str = 'USPS Large Box';
                break;
            case 7:
                $str = 'USPS padded Envelope';
                break;
            case 8:
                $str = 'FEDEX本地邮局派送';
                break;
		 case 9:
                $str = 'UPS本地邮局派送';
                break;
            default:
                $str = 'Unknow';
                break;


        }
        return $str;

    }

    public function ajaxLoadTplName()
    {
        $sql = "select tpl_name as 'text',tpl_code as 'id' from mt_shipping_fee_basic group by tpl_code";
        $res = $this->db->query($sql)->result_array();
        echo(json_encode($res));
        exit;
    }

    public function ajaxLoadCountry()
    {
        $gp = gp();
        $keys = strtolower(trim($gp['keys']));
        $sql = "select * from `mt_shipping_country` order by  `iso_code_2` asc";
        if (!empty($keys)) {
            $sql = "select * from `mt_shipping_country` where `iso_code_2` like '%" . $keys . "%' or `name`  like '%" . $keys . "%' order by  `iso_code_2` asc";
        }
        $res = $this->db->query($sql)->result_array();
        $result = array();
        foreach ($res as $k => $v) {
            $result[$k]['id'] = $v['iso_code_2'];
            $result[$k]['text'] = $v['name'];
            $children = $this->db->query("select id,`name` as 'text'  from `mt_shipping_zone` where `country_id` = '" . intval($v['id']) . "' and `status` =1")->result_array();
            if ($children) {
                $result[$k]['state'] = 'closed';
                $result[$k]['children'] = $children;
            }
        }
        echo(json_encode($result));
        exit;
    }

    /**
     * ajax添加运费模板
     */
    public function ajaxAddShippingTpl()
    {
        $gp = gp();
        $tpl_name = trim($gp['tplname']); //模板名称

        $tpl_code = trim($gp['tplcode']); //模板编码
        if (strpos($tpl_code , 'ST-') == '') {
            $tpl_code = 'ST-' . time(); //模板编号
        }


        $pickup_country = trim($gp['selCountry']); //发货个国家地区
        $shipping_type = trim($gp['selType']); //发货类型
        $status = 1; //状态，m默认为1启用，0停用

        $delivery_cost_fee = explode(',' , trim($gp['costFee']));
        $delivery_fee = explode(',' , trim($gp['costFee']));
        $delivery_country = explode(',' , trim($gp['delCountry']));
        $delivery_citys = trim($gp['selCitys']);
        $begin_weight = explode(',' , trim($gp['bgW']));
        $end_weight = explode(',' , trim($gp['edW']));
        //以下字段保留，暂时不用，后期扩展 begin
        $merchant_num = '0'; //商家id
        $model_id = '0'; //产品型号
        $brand_id = '0'; //品牌id
        $category_id = '0'; //分类id
        //以上字段保留，暂时不用，后期扩展 end
        for ($ii = 0 ; $ii < count($delivery_cost_fee) ; $ii++) {
            $this->shipping_model->AddShippingTpl($category_id , $tpl_name , str_replace('_' , ',' , $delivery_country[$ii]) , $delivery_cost_fee[$ii] , $delivery_fee[$ii] , $pickup_country , $begin_weight[$ii] , $end_weight[$ii] , $merchant_num , $model_id , $brand_id , $status , $shipping_type , $tpl_code , $delivery_citys);
        }

        echo('1');
        exit;
    }

    /**
     * 删除模板
     */
    public function ajaxDelById()
    {
        $gp = gp();
        $id = intval(trim($gp['id']));
        $res = $this->shipping_model->DelShippingTpl($id);
        echo($res);
        exit;
    }

    /**
     * 批量删除运费模板
     */
    public function ajaxDelTpls()
    {
        $gp = gp();
        $ids = trim($gp['ids']);
        $res = $this->shipping_model->DelShippingTpls($ids);

        echo($res);
        exit;
    }

    /**
     *
     */
    public function ajaxLoadTpl()
    {
        $gp = gp();
        $id = trim($gp['id']);
        $res = $this->shipping_model->GetShippingTpl($id);
        echo(json_encode($res));
        exit;
    }

    /**
     * 加载自定义费用
     */
    public function ajaxLoadPriceCuz()
    {
        $gp = gp();
        $merchant_num = ''; //商户编号
        $category_id = ''; //产品型号
        $model_id = ''; //产品型号
        $brand_id = ''; //品牌
        $pickup = ''; //起始地
        $deliveay = ''; //目的地
        $sql = 'select * from `mt_shipping_fee_customize`';
        $res = $this->db->query($sql)->result_array();
        echo(array('total' => count($res) , 'rows' => $res));
        exit;
    }

    public function ajaxMdyTpl()
    {
        $gp = gp();
        $mdyName = trim($gp['mdyName']);
        $mdyBgW = trim($gp['mdyBgW']);
        $mdyEdW = trim($gp['mdyEdW']);
        $mdyCostFee = trim($gp['mdyCostFee']);
        $mdyFee = trim($gp['mdyFee']);
        $mdyPickup = trim($gp['mdyPickup']);
        $hidId = trim($gp['hidId']);
        $mdyType = trim($gp['mdyType']);
        $mdyDelivery = trim($gp['mdyDelivery']);

        $hidTplCode = trim($gp['hidTplCode']);
        $hidOldTpl = trim($gp['hidOldTpl']);

        $sql = sprintf("UPDATE `mt_shipping_fee_basic` SET `delivery_country` = '%s', `delivery_cost_fee` = '%s',`delivery_fee` = '%s', `pickup_country` = '%s', `begin_weight` = '%s', `end_weight` = '%s', `shipping_type` = '%s' WHERE	`id` = '%s'" , $mdyDelivery , $mdyCostFee , $mdyFee , $mdyPickup , $mdyBgW , $mdyEdW , $mdyType , $hidId);
        $res = $this->db->query($sql);
        //修改模板名称
        if ($hidOldTpl != $mdyName) {
            $this->db->query(sprintf("UPDATE `mt_shipping_fee_basic` set `tpl_name` = '%s' where `tpl_code` ='%s' " , $mdyName , $hidTplCode));
        }
        echo(json_encode($res));
        exit;
    }

    /*     * ******************************************************************************************************************************************** */
    /* 以下为自定义运费代码 */

    public function customize()
    {
        $data = array();
        $data['listCountry'] = $this->db->query("select * from mt_country")->result_array();

        $cates = $this->db->query("select id,name_ch,name_en from mt_product_category")->result_array();
        foreach ($cates as $k => $v) {
            $cates[$k]['name'] = $v['name_' . $this->curLang];
        }
        $data['categories'] = $cates;
        $this->load->view('defaults/shipping/customize' , $data);
    }

    public function ajaxLoadCustomizePrice()
    {
        $gp = gp();
        $page = intval($gp['page']);
        $rows = intval($gp['rows']);

        $dtPickup = trim($gp['dtPickUp']);
        $dtTplname = trim($gp['dtTplname']);

        $where = ' where 1=1 ';
        if (!empty($dtPickup)) {
            $where = $where . " and `pickup_country` like '%" . $dtPickup . "%'";
        }

        if (!empty($dtDelivery)) {
            $where = $where . " and `delivery_country` like '%" . $dtDelivery . "%'";
        }

        if (!empty($dtTplname)) {
            $where = $where . " and `tpl_name` like '%" . $dtTplname . "%'";
        }
        //计算总条数
        $sql_total = 'select count(`id`) as cnt from `mt_shipping_fee_customize`' . $where;
        $res_total = $this->db->query($sql_total)->row_array();
        $total = intval($res_total['cnt']);
        //计算总条数


        $sql = 'select * from `mt_shipping_fee_customize` ' . $where . ' order by  model_id desc';
        if ($page > 0 && $rows > 0) {
            $start = (($page - 1) * $rows);
            $sql = $sql . ' limit ' . $start . ' , ' . $rows;
        }


        $res = $this->db->query($sql)->result_array();
        foreach ($res as $k => $v) {
            $res[$k]['weight'] = $v['product_weight'];
            $res[$k]['shipping_type'] = $v['shipping_type'] == 1 ? "DHL" : "UPS";

            //品牌名称
            $brand = $this->common_model->selectFirst('product_brand' , array('id' => $v['brand_id']));

            $res[$k]['brand_name'] = $brand['name'];

            //型号名称
            $model = $this->common_model->selectFirst('product_model' , array('id' => $v['model_id']));
            $res[$k]['model_name'] = $model['name'];
        }
        echo(json_encode(array('total' => $total , 'rows' => $res)));

        exit;
    }

    public function ajaxLoadCountryItem()
    {
        $gp = gp();
        $keys = strtolower(trim($gp['keys']));
        $sql = "select * from `mt_shipping_country`  order by `iso_code_2`  asc";
        if (!empty($keys)) {
            $sql = "select * from `mt_shipping_country` where `iso_code_2` like '%" . $keys . "%' or `name`  like '%" . $keys . "%' order by `iso_code_2`  asc";
        }
        $res = $this->db->query($sql)->result_array();
        $result = array();
        foreach ($res as $k => $v) {
            $result[$k]['id'] = $v['iso_code_2'];
            $result[$k]['text'] = $v['iso_code_2'];
            $children = $this->db->query("select id,`name` as 'text'  from `mt_shipping_zone` where `country_id` = '" . intval($v['id']) . "' and `status` =1 ")->result_array();
            if ($children) {
                $result[$k]['state'] = 'closed';
                $result[$k]['children'] = $children;
            }
        }
        echo(json_encode($result));
        exit;
    }

    /**
     * ajax添加自定义运费
     */
    public function ajaxAddShippingCustomize()
    {
        $gp = gp();
        $rows = json_decode($gp['data']);
        $category_id = $rows->category_id; //产品分类
        $delivery_country = $rows->delivery_country; //收获地区
        $delivery_citys = ''; //收货城市
        $delivery_cost_fee = $rows->delivery_cost_fee; //预计成本
        $delivery_fee = $rows->delivery_fee; //物流费
        $pickup_country = $rows->pickup_country; //发货地区
        $product_weight = $rows->product_weight; //起始重量
        $add_time = time(); //时间
        $add_user = serialize($this->users['account']); //添加人
        $merchant_num = 0; //商家id，预留，暂时不用
        $model_id = $rows->model_name; //型号id
        $brand_id = $rows->brand_name; //品牌id
        $status = 1; //状态，1为启用，0为禁用
        $shipping_type = $rows->shipping_type;
        $sql = sprintf("INSERT INTO `mt_shipping_fee_customize`( `category_id`, `delivery_country`, `delivery_citys`, `delivery_cost_fee`, `delivery_fee`, `pickup_country`, `product_weight`,  `add_time`, `add_user`, `merchant_num`, `model_id`, `brand_id`, `status`, `shipping_type`) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" , $category_id , $delivery_country , $delivery_citys , $delivery_cost_fee , $delivery_fee , $pickup_country , $product_weight , $add_time , $add_user , $merchant_num , $model_id , $brand_id , $status , $shipping_type);
        $res = $this->db->query($sql);
        echo(json_encode($res));
        exit;
    }

    /**
     * ajax修改自定义运费
     */
    public function ajaxMdyShippingCustomize()
    {
        $gp = gp();
        $rows = json_decode($gp['data']);
        $sql = sprintf("UPDATE `mt_shipping_fee_customize` SET `category_id` = '%s', `delivery_country` = '%s', `delivery_cost_fee` = '%s',`delivery_fee` = '%s', `pickup_country` = '%s',`product_weight` = '%s',`model_id` = '%s', `brand_id` = '%s',`status` = '%s',`shipping_type` = '%s'  WHERE `id` = '%s'" , $rows->category_id , $rows->delivery_country , $rows->delivery_cost_fee , $rows->delivery_fee , $rows->pickup_country , $rows->product_weight , $rows->model_id , $rows->brand_id , $rows->status , $rows->shipping_type , $rows->id);
        $res = $this->db->query($sql);
        die($res);
        exit;
    }

    /**
     *
     * ajax删除运费
     */
    public function ajaxDelShippingCustomize()
    {
        $gp = gp();
        $id = intval(trim($gp['id']));
        $sql = sprintf("delete from `mt_shipping_fee_customize` where `id` = '%s'" , $id);
        $res = $this->db->query($sql);
        echo($res);
        exit;
    }

    /**
     * ajax加载型号
     */
    public function ajaxLoadModel()
    {
        $gp = gp();
        $id = intval(trim($_GET['cid']));

        $catge_sap_id = 0;
        $mt_p = $this->common_model->selectFirst('mt_product_category' , array('id' => $id));

        //获取sapid
        if (strpos($mt_p['sap_id'] , '_')) {
            $catge_sap_id = intval(strstr($mt_p['sap_id'] , '_' , TRUE));
        }
        else {
            $catge_sap_id = intval($mt_p['sap_id']);
        }

        //获取product_type的id
        $mt_ptype = $this->common_model->selectFirst('product_type' , array('id' => $catge_sap_id));

        $mt_pbrand = $this->common_model->selectFirst('product_brand' , array('id' => $_GET['bid']));

        $sql = sprintf("select psa.`tid`,psa.`bid`,psa.`mid`,pb.`name`,pb.`id` from `product_model` pb inner join  `product_association_b` psa on pb.`sap_id` = psa.`mid` where psa.`tid` ='%s' and psa.`bid`='%s' group by psa.mid" , intval($mt_ptype['id']) , $mt_pbrand['sap_id']);

        $res = $this->db->query($sql)->result_array();
        echo(json_encode($res));
        exit;
    }

    /**
     *
     */
    public function ajaxLoadBrand()
    {
        $gp = gp();
        $id = intval(trim($_GET['cid']));

        $catge_sap_id = 0;
        $mt_p = $this->common_model->selectFirst('mt_product_category' , array('id' => $id));

        //获取sapid
        if (strpos($mt_p['sap_id'] , '_')) {
            $catge_sap_id = intval(strstr($mt_p['sap_id'] , '_' , TRUE));
        }
        else {
            $catge_sap_id = intval($mt_p['sap_id']);
        }

        //获取product_type的id
        $mt_ptype = $this->common_model->selectFirst('product_type' , array('id' => $catge_sap_id));


        $sql = sprintf("select psa.`tid`,psa.`bid`,pb.`name`,pb.`id` from `product_brand` pb inner join  `product_association_b` psa on pb.`sap_id` = psa.`bid` where psa.`tid` ='%s' group by psa.bid" , intval($mt_ptype['id']));
        $res = $this->db->query($sql)->result_array();
        echo(json_encode($res));
        exit;
    }

    /**
     * ajax根据型号加载重量
     */
    public function ajaxLoadModelWeight()
    {
        $gp = gp();
        $id = intval(trim($gp['id']));
        $weight = $this->common_model->selectFirst('mt_shipping_product_weight' , array('mid' => $id));
        if ($weight) {
            echo($weight['weight']);
        }
        else {
            echo('0');
        }
        exit;

    }

    public function px4() {
        $this->load->model('px4_model');
        $this->load->view('defaults/shipping/4px');
    }

    public function ajaxDo4px() {
        $this->load->model('px4_model');
        $gp = gp();
        $state = $gp['state'];
        $city = $gp['city'];
        $name = $gp['name'];
        $addr = $gp['addr'];
        $zip = $gp['zip'];
        $phone = $gp['phone'];
        $code = $gp['code'];
        $res = $this->px4_model->do4px($state, $city, $name, $addr, $zip, $phone, $code);
        if ($res) {
            $this->load->library('barcode');
            $type = "C128";
            $w = '3';
            $h = '55';
            //$code = $this->barcode->getBarcodeHTML($gp['order_code'] , $type);
            $code = '<div><img style="" src="data:image/png;base64,' . $this->barcode->getBarcodePNG($res, $type, 2, 65) . '"/><br>' . $res . '<br/><img  src="data:image/png;base64,' . $this->barcode->getBarcodePNG('TOMREPAIRAPI001', $type, 2, 65) . '"/><br>TOMREPAIRAPI001<br></div>';
            echo($code);
            die;
        }

        die("faild");
    }
    
    /**
     * ajax获取试算的价格
     */
    public function ajaxGetTrialPrice()
    {
        $gp = gp();
        $ctBeginWeight = $gp['ctBeginWeight'];//启示重量
        $ctEndWeight = $gp['ctEndWeight'];//结束重量
        $ctFromCountry = $gp['ctFromCountry'];//发货国家
        $ctToCountry = $gp['ctToCountry'];//目的国家

        $sql = sprintf("select * from `mt_shipping_fee_basic` where `delivery_country` like '%s' and `pickup_country` = '%s' and `begin_weight` <= %s and `end_weight` >= %s" , '%' . $ctToCountry . '%' , $ctFromCountry , $ctBeginWeight , $ctEndWeight);
        //die($sql);
        $res = $this->db->query($sql)->result_array();
        echo(json_encode(array('total' => count($res) , 'rows' => $res)));
        exit;
    }

}
